package com.boco.blch.dispatcher.service;

import com.asiainfo.uap.util.des.EncryptInterface;
import com.boco.blch.analysiser.service.ResultAnalysisService;
import com.boco.blch.analysiser.util.HttpUtil;
import com.boco.blch.dispatcher.dao.BigDataDao;
import com.boco.blch.dispatcher.params.SingleLoginParams;
import com.boco.blch.dispatcher.po.*;
import com.boco.blch.dispatcher.util.FileUtil;
import com.boco.blch.dispatcher.util.HttpXmlClient;
import com.boco.blch.dispatcher.util.NetworkSegmentUtil;
import com.boco.blch.runner.parameter.SingleLoginParam;
import com.boco.blch.runner.service.ShellExecuteService;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.net.URL;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class BigDataServiceImpl implements BigDataService {

    @Autowired
    private BigDataDao bigDataDao;

    private Logger log = Logger.getLogger(BigDataServiceImpl.class);

    /**
     * 根据传递的合规编号完成相应的合规检查以及结果入库
     */
    @Override
    @Transactional
    public String compliantService(String DeviceId, String Ip, String Port, String User, String UserEncryptd,
                                   String Password, String PasswordEncryptd, compliant comp, String taskNo) {
        // TODO Auto-generated method stub

		/*
         * //根据传递的合规编号查询出相关信息 Map<String, String> map = new HashMap<String,
		 * String>(); map.put("compliantnumber", compliantnumber);
		 * map.put("plantform", plantform); map.put("nodeType", nodeType);
		 * log.info(map); compliant comp = bigDataDao.searchCompliant(map);
		 * if(comp == null){ throw new
		 * IllegalArgumentException("找不到检查项：plantform=" + plantform +
		 * "nodeType="+nodeType+"&compliantnumber=" + compliantnumber); }
		 */
        // 获取脚本文件信息
        String scriptcontext = comp.getScriptcontext();

        // 解析相关脚本文件信息并且完成指令下发返回执行结果
        String plantformName = bigDataDao.getPlantformName(comp.getPlantform());
        String[] param = {Ip, Port, User, UserEncryptd, Password, PasswordEncryptd, comp.getCompliantnumber(),
                plantformName, scriptcontext};
        String result = InstructionIssued(param);

        // 对执行结果进行解析获取脚本指令执行结果
        if (result != null) {
            String analysisResult = null;

            // 如果脚本带了期望结果的话，就交由期望结果解析，否则还是交给解析服务处理
            if (StringUtils.isEmpty(comp.getExpectResult())) {
                analysisResult = ResultAnalysis(comp.getCompliantnumber(), plantformName, comp.getNodeType() + "",
                        result);
            } else {
                analysisResult = serviceWithExceptResult(result, comp);
            }

            if (analysisResult != null) {
                // 合规检查结果入库
                String id = saveResult(DeviceId, comp.getCompliantnumber(), Ip, result, analysisResult, taskNo,
                        comp.getPlantform() + "", comp.getNodeType() + "");
                return id;
            } else {
                String id = saveResult(DeviceId, comp.getCompliantnumber(), Ip, result, "false", taskNo,
                        "" + comp.getPlantform(), comp.getNodeType() + "");
                log.error("结果解析返回为空");
                return id;
            }

        } else {
            // 合规检查结果入库
            String id = saveResult(DeviceId, comp.getCompliantnumber(), Ip, "指令下发接口调用失败", "false", taskNo,
                    comp.getPlantform() + "", comp.getPlantform() + "");
            log.error("指令下发返回结果为空");
            return id;
        }

    }

    /**
     * 完成脚本重组以及调用指令下发接口
     *
     * @param param
     * @return
     */
    private String InstructionIssued(String[] param) {
        String scriptcontext = param[8];
        String compliantnumber = param[6];
		/*
		 * String context = ""; if(scriptcontext != null &&
		 * !scriptcontext.trim().isEmpty()){ String[] scr =
		 * scriptcontext.split(";"); if(scr.length == 1) context = scr[0]; else{
		 * context = "touch "+compliantnumber+".sh;"; for(String str : scr){
		 * context = context+str+" >> "+compliantnumber+".sh;"; } context =
		 * context+"chmod u+x "
		 * +compliantnumber+".sh;"+"./"+compliantnumber+".sh;"; } }
		 */
        // 判断指令是否为空，为空则不会调用指令下发接口
        if (scriptcontext != null && !scriptcontext.trim().isEmpty()) {
            SAXReader saxReader = new SAXReader();
            URL url = this.getClass().getClassLoader().getResource("ipconfig.xml");
            try {
                Document document = saxReader.read(url);
                Element config = document.getRootElement();
                String execUrl = config.elementText("ShellCommand_URL");

                Map<String, String> params = new HashMap<String, String>();
                params.put("Ip", param[0]);
                params.put("Port", param[1]);
                params.put("User", param[2]);
                params.put("UserEncryptd", param[3]);
                params.put("Password", param[4]);
                params.put("PasswordEncryptd", param[5]);
                params.put("plantform", param[7]);
                params.put("ShellCommand", scriptcontext);

                String xml = HttpXmlClient.post(execUrl, params);
                // 解析返回的xml字符串
                Document doc = DocumentHelper.parseText(xml);
                Element root = doc.getRootElement();
                String result = root.elementText("Result");
                if (result.equals("Success")) {
                    Element opDetail = root.element("opDetail");
                    String CommandResult = opDetail.elementText("CommandResult");
                    return CommandResult;
                } else {
                    String ErrorCode = root.elementText("ErrorCode");
                    String ErrorMessage = root.elementText("ErrorMessage");
                    log.error("指令下发执行结果不成功" + ErrorCode + ErrorMessage);
                    return "Error;" + "ErrorCode:" + ErrorCode + " ErrorMessage:" + ErrorMessage;
                }
            } catch (Exception e) {
                log.error(e.getMessage() + "ShellCommand_Execute Interface Execute Fail 指令下发接口调用失败");
                return null;
            }
        } else {
            log.error("ShellCommand is null  脚本指令为空");
            return null;
        }

    }

    /**
     * 调用结果解析接口，获取指令执行结果
     *
     * @param serialNo
     * @param result
     * @return
     */
    private String ResultAnalysis(String serialNo, String plantform, String nodeType, String result) {

        try {
            log.info("###发送结果到解析服务：serialNo:" + serialNo + " ;plantform:" + plantform + " ;nodeType:" + nodeType
                    + " ;result:" + subString(result, 100));
            String Result = ResultAnalysisService.service(serialNo, plantform, nodeType, result);
            return Result;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("ResultAnalysis_Execute Interface Execute Fail 结果解析接口调用失败");
            return null;
        }
    }

    private String saveResult(String deviceId, String compliantnumber, String Ip, String ShellBackResult,
                              String IsSuccess, String taskNo, String plantform, String nodeType) {
        compliant_Result result = new compliant_Result();
        Date date = new Date();
        result.setCheckSN(compliantnumber + date);
        result.setCheckTime(date);
        result.setDeviceIP(Ip);
        result.setDeviceId(deviceId);
        result.setCompliantnumber(compliantnumber);
        result.setShellBackResult(ShellBackResult);
        if (IsSuccess.equals("0")) {
            result.setIsAuto(0);
            result.setIsSuccess(1);
            result.setReviseStatus("1");
        } else if (IsSuccess.equals("1")) {
            result.setIsAuto(0);
            result.setIsSuccess(0);
            result.setReviseStatus("0");
        } else if (IsSuccess.equals("2")) {
            result.setIsAuto(1);
            result.setIsSuccess(0);
            result.setReviseStatus("0");
        }

        result.setTaskNo(taskNo);
        result.setPlantform(plantform);
        result.setNodeType(nodeType);
        bigDataDao.saveResult(result);

        String id = String.valueOf(result.getId());
        return id;
    }

    public List<compliant> getCompliantByCompName(String compName, String plantform, String nodeType) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("compliantName", compName);
        map.put("plantform", plantform);
        map.put("nodeType", nodeType);
        return bigDataDao.getCompliantByCompName(map);
    }

    @Override
    public int getCountByName(String compliantName, String plantform, String nodeType) {
        return getCompliantByCompName(compliantName, plantform, nodeType).size();
    }

    /**
     * 如果compliant里面带有exceptresult，就不用调用解析服务，而是采用字符串匹配或者正则匹配的方法来判定是否合规
     *
     * @return
     */
    private String serviceWithExceptResult(String echoResult, compliant compliant) {
        String expectResult = compliant.getExpectResult();
        Pattern p = Pattern.compile(expectResult);
        Matcher m = p.matcher(echoResult);
        boolean b = m.matches();
        return String.valueOf(b);
    }

    private String subString(String source, int length) {
        if (source.length() > length)
            return source.substring(0, length) + "...(由于数据达到 " + source.length() + " 位，已省略" + length + "位后的字符)";
        else
            return source;
    }

    // =====================================================================================

    /**
     * 单次登录，一次执行
     */
    @Override
    public void execOnSingleLogin(SingleLoginParams slp) {
        // 0.检查taskNo是否为空，如果是空就自动创建一个
        if (StringUtils.isEmpty(slp.getTaskNo())) {
            slp.setTaskNo(getTaskNo());
        }

        // 1. 组装发送参数
        Device device = bigDataDao.getDeviceById(slp.getDeviceId());
        List<compliant> compList = getCompliantList(slp, device);

        String scriptCollection = getSeperatorScript(compList);
        // 2. 发送检查,收集回显信息

        SingleLoginParam sp = new SingleLoginParam();
        sp.setAccount(device.getUsername());
        sp.setIp(device.getIp());
        sp.setPassword(device.getPassword());
        sp.setPort(device.getPort());
        sp.setScriptcollection(scriptCollection);

        JSONArray resultArray = ShellExecuteService.execOnSingleLogin(sp);

        if (resultArray != null && resultArray.size() != 0) {
            for (int i = 0; i < resultArray.size(); i++) {
                JSONObject resultObj = resultArray.getJSONObject(i);
                if (resultObj == null) {
                    continue;
                }
                String analysisResult = ResultAnalysis(resultObj.getString("compliantnumber"),
                        getPlantformName(device.getPlantform()), device.getNodeType() + "",
                        resultObj.getString("result"));

                if (analysisResult != null) {
                    // 合规检查结果入库
                    saveResult(slp.getDeviceId() + "", resultObj.getString("compliantnumber"), device.getIp(),
                            resultObj.getString("result"), analysisResult, slp.getTaskNo(), device.getPlantform() + "",
                            device.getNodeType() + "");
                } else {
                    saveResult(slp.getDeviceId() + "", resultObj.getString("compliantnumber"), device.getIp(),
                            resultObj.getString("result"), "1", slp.getTaskNo(), device.getPlantform() + "",
                            device.getNodeType() + "");
                }
            }
        }
    }

    private String getTaskNo() {
        return FileUtil.getDate() + "_" + FileUtil.generateMixed(6);
    }

    private List<compliant> getCompliantList(SingleLoginParams slp, Device device) {
        Map<String, String> paramsMap = new HashMap<String, String>();
        paramsMap.put("plantform", "" + device.getPlantform());
        paramsMap.put("nodeType", "" + device.getNodeType());
        paramsMap.put("compliantNames", slp.getComponentIds());
        return bigDataDao.getCompliantByCompNames(paramsMap);
    }

    /**
     * 得到post过去的脚本，已经加好分割符号了。
     * json格式。[{compliantnumber:"xxxxx",script:"xxxxxxx"}]
     *
     * @param list
     * @return
     */
    private String getSeperatorScript(List<compliant> list) {
        JSONArray array = new JSONArray();
        if (list != null && list.size() != 0) {
            for (compliant c : list) {
                JSONObject obj = new JSONObject();
                obj.put("compliantnumber", c.getCompliantnumber());
                obj.put("script", c.getScriptcontext());
                array.element(obj);
            }
        }

        return array.toString();
    }

    private String getPlantformName(Integer plantformId) {
        return bigDataDao.getPlantformName(plantformId);
    }

    @Override
    public void hotkeyCheck(String ip) {
        Device device = bigDataDao.getDeviceByIp(ip);
        SingleLoginParams slp = new SingleLoginParams();
        slp.setComponentIds(getDeviceComponent(device));
        slp.setDeviceId(device.getId());
        slp.setTaskNo(getTaskNo());
        execOnSingleLogin(slp);
    }

    private String getDeviceComponent(Device device) {
        String userName = device.getUsername();
        String password = device.getPassword();
        Map<String, String> paraMap = new HashMap<String, String>();
        paraMap.put("username", userName);
        paraMap.put("password", password);
        paraMap.put("ip", device.getIp());

        String url = "";
        String body = HttpUtil.sendPost(url, "");

        return paraseBody(body);
    }

    private String paraseBody(String body) {
        return "";
    }

    @Override
    public void baselineScan(String ip, String component, HttpServletResponse response) {
        SingleLoginParams singleloginparams = new SingleLoginParams();
        Document errorMessage = DocumentHelper.createDocument();
        Element root = errorMessage.addElement("root");
        boolean error = false;

        //查询传入的组件号ID
        if (!component.equals("all")) {
            String[] componentCodeNames;
            StringBuilder componentIds = new StringBuilder();
            componentCodeNames = component.split(",");
            Properties prop = new Properties();
            InputStream is = BigDataServiceImpl.class
                    .getResourceAsStream("/dispatcher/componentCodeName.properties");
            try {
                prop.load(is);
                is.close();
                Pattern pattern = Pattern.compile("\\d+");
                for (String componentCodeName : componentCodeNames) {
                    Matcher matcher = pattern.matcher(componentCodeName);
                    if (matcher.matches() && Integer.parseInt(componentCodeName) <= prop.size()) {
                        componentIds.append(componentCodeName + ",");
                    } else if (prop.getProperty(componentCodeName) != null) {
                        componentIds.append(prop.getProperty(componentCodeName) + ",");
                    } else {
                        error = true;
                        Element msg = root.addElement("msg");
                        msg.setText("有未知的组件:" + componentCodeName);
                    }
                }
                if (!error) {
                    componentIds.deleteCharAt(componentIds.length() - 1);
                }
                singleloginparams.setComponentIds(componentIds.toString());
            } catch (Exception e) {
                error = true;
                Element msg = root.addElement("msg");
                msg.setText("无法获得组件列表");
                e.printStackTrace();
            }
        }

        //对传入ip进行分割
        String[] ips;
        if (ip.lastIndexOf("-") > 0) {
            String[] ips1 = ip.split("-");
            ips = NetworkSegmentUtil.Analyse(ips1[0], ips1[1]);
        } else {
            ips = ip.split(",");
        }


        // 遍历ip查出设备ID
        Device device = new Device();
        List<Device> devices = new ArrayList<Device>();
        for (String i : ips) {
            device = bigDataDao.getDeviceByIp(i);
            if (device == null) {
                error = true;
                Element msg = root.addElement("msg");
                msg.setText("有未知的ip地址:" + i);
            } else {
                devices.add(device);
            }
        }

        //返回结果
        try {
            response.setCharacterEncoding("utf-8");
            if (!error) {
                singleloginparams.setTaskNo(getTaskNo());
                response.getWriter().print(singleloginparams.getTaskNo());
            } else {
                OutputFormat of = OutputFormat.createPrettyPrint();
                of.setEncoding("UTF-8");
                of.setIndent(true);
                of.setIndent("    ");
                of.setNewlines(true);
                StringWriter sw = new StringWriter();
                XMLWriter xw = new XMLWriter(sw, of);
                xw.write(errorMessage);
                xw.close();
                response.getWriter().print(errorMessage.toString());
            }
            response.getWriter().flush();
            response.getWriter().close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


        // 如果参数无误，进行扫描
        if (!error) {
            CheckQuickResult checkquickresult = new CheckQuickResult();
            checkquickresult.setDeviceCount(devices.size());
            checkquickresult.setTaskNo(singleloginparams.getTaskNo());
            checkquickresult.setDownloadUrl(
                    "http://localhost:8085/BOCO_ReportGenerate?taskNo=" + singleloginparams.getTaskNo());
            checkquickresult.setCreateUserName("admin");
            checkquickresult.setStatus(1);
            checkquickresult.setStartTime(new Date());
            checkquickresult.setPlainName(FileUtil.getDate());
            bigDataDao.insertCheckQuickResult(checkquickresult);

            // 交由检查模块进行检查
            for (Device i : devices) {
                if (component.equals("all")) {
                    Properties prop = new Properties();
                    Properties prop1 = new Properties();
                    try {
                        InputStream is = BigDataServiceImpl.class
                                .getResourceAsStream("/dispatcher/scanurl.properties");
                        InputStream is1 = BigDataServiceImpl.class
                                .getResourceAsStream("/dispatcher/componentCodeName.properties");
                        prop.load(is);
                        prop.load(is1);
                        is.close();
                        is1.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    String url = prop.getProperty("url");
                    String scanresult = HttpUtil.sendPost(url, "ip=" + i.getIp() + "&username=" + i.getUsername() + "&password=" + EncryptInterface.desEncryptData(i.getPassword()));
                    Gson gson = new GsonBuilder().create();
                    ModulesScan modulesscan = gson.fromJson(scanresult, ModulesScan.class);
                    StringBuilder componentsIds = new StringBuilder();
                    for (ast j : modulesscan.getAst()) {
                        componentsIds.append(prop1.getProperty(j.getTypeName()) + ",");
                    }
                    componentsIds.deleteCharAt(componentsIds.length() - 1);
                    singleloginparams.setComponentIds(componentsIds.toString());
                }
                singleloginparams.setDeviceId(i.getId());
                execOnSingleLogin(singleloginparams);
            }

            // 结果进行统计
            List<compliant_Result> results = bigDataDao.getCompliantResultByTaskNo(singleloginparams.getTaskNo());
            int compliantCount = 0;
            int manualCount = 0;
            double compliantRate;
            if (results != null &&results.size()!=0) {
                for (compliant_Result i : results) {
                    if (i.getIsSuccess() == 1) {
                        compliantCount++;
                    }
                    if (i.getIsAuto() == 0) {
                        manualCount++;
                    }
                }
                compliantRate = (double) compliantCount / (double) results.size();
            } else {
                compliantRate = 0.0;
            }
            checkquickresult.setSuccessCount(compliantCount);
            checkquickresult.setCompliantCount(results.size());
            checkquickresult.setEndTime(new Date());
            checkquickresult.setSuccessRate(compliantRate);
            checkquickresult.setStatus(0);
            checkquickresult.setManualCount(manualCount);
            checkquickresult.setFailedCount(results.size() - compliantCount);
            bigDataDao.updateCheckQuickResult(checkquickresult);
        }
    }

    @Override
    public String balineStatus(String taskNo) {
        Document document = DocumentHelper.createDocument();
        Element root = document.addElement("root");
        Element msg = root.addElement("msg");
        Element code = root.addElement("code");

        CheckQuickResult result = bigDataDao.getCheckQuickResultByTaskNo(taskNo);
        if (result == null) {
            msg.setText("错误的任务序号");
            code.setText("100");
        } else {
            msg.setText("success");
            code.setText("0");
            Element statusCode = root.addElement("statusCode");
            Element status = root.addElement("status");
            if (result.getStatus().equals(0)) {
                statusCode.setText("0");
                status.setText("扫描完成");
            } else {
                statusCode.setText("1");
                status.setText("扫描中");
            }
        }
        OutputFormat of = OutputFormat.createPrettyPrint();
        of.setEncoding("UTF-8");
        // of.setSuppressDeclaration(true);
        of.setIndent(true);
        of.setIndent("    ");
        of.setNewlines(true);
        StringWriter sw = new StringWriter();
        try {
            XMLWriter xw = new XMLWriter(sw, of);
            xw.write(document);
            xw.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sw.toString();
    }

    @Override
    public String baselineResult(String taskNo) {
        Document document = DocumentHelper.createDocument();
        Element root = document.addElement("root");
        Element msg = root.addElement("msg");
        Element code = root.addElement("code");
        CheckQuickResult quickResult = bigDataDao.getCheckQuickResultByTaskNo(taskNo);
        if (quickResult == null) {
            msg.setText("错误的任务序号");
            code.setText("100");
        } else if (quickResult.getSuccessRate() == null) {
            msg.setText("未完成的任务");
            code.setText("200");
        } else {
            msg.setText("success");
            code.setText("0");
            Element deviceCount = root.addElement("deviceCount");
            deviceCount.setText(quickResult.getDeviceCount().toString());
            Element complianceRate = root.addElement("complianceRate");
            complianceRate.setText((quickResult.getSuccessRate() * 100) + "%");
            Element totalCount = root.addElement("totalCount");
            totalCount.setText(quickResult.getCompliantCount().toString());
            Element complianceCount = root.addElement("complianceCount");
            complianceCount.setText(quickResult.getSuccessCount().toString());
            Element uncomplianceCount = root.addElement("uncomlianceCount");
            uncomplianceCount.setText(quickResult.getFailedCount().toString());
            Element results = root.addElement("results");
            List<compliant_Result> compliantResults = bigDataDao.getCompliantResultByTaskNo(taskNo);
            List<compliant_Result> compliant_Result = new ArrayList<compliant_Result>();
            compliant_Result.add(compliantResults.get(0));
            for (int i = 1; i < compliantResults.size(); i++) {
                if (!(compliant_Result.get(0).getDeviceIP().equals(compliantResults.get(i).getDeviceIP()))
                        || (i == compliantResults.size() - 1)) {

                    if (i == compliantResults.size() - 1) {
                        compliant_Result.add(compliantResults.get(i));
                    }

                    int deviceComplianceCount = 0;
                    for (int j = 0; j < compliant_Result.size(); j++) {
                        if (compliant_Result.get(j).getIsSuccess() == 1) {
                            deviceComplianceCount++;
                        }
                    }
                    float deviceComplianceRate = (float) deviceComplianceCount / (float) compliant_Result.size();
                    Element result = results.addElement("result");
                    Element ip = result.addElement("ip");
                    ip.setText(compliant_Result.get(0).getDeviceIP());
                    ip.addAttribute("complianceRate", String.valueOf(deviceComplianceRate * 100) + "%");
                    ip.addAttribute("complianceCount", String.valueOf(deviceComplianceCount));
                    ip.addAttribute("uncomplianceCount",
                            String.valueOf(compliant_Result.size() - deviceComplianceCount));
                    ip.addAttribute("totalCount", String.valueOf(compliant_Result.size()));

                    List<compliant_Result> component_Result = new ArrayList<compliant_Result>();
                    component_Result.add(compliant_Result.get(0));
                    List<compliant> compliants = new ArrayList<compliant>();
                    compliants.add(bigDataDao.getCompliantByCompliantResult(component_Result.get(0)));
                    for (int j = 1; j < compliant_Result.size(); j++) {
                        compliant compliant = bigDataDao.getCompliantByCompliantResult(compliant_Result.get(j));
                        if (!(compliant.getStandard_Source().getComp_Name()
                                .equals(compliants.get(0).getStandard_Source().getComp_Name()))
                                || (j == compliant_Result.size() - 1)) {
                            if (j == compliant_Result.size() - 1) {
                                compliants.add(compliant);
                                component_Result.add(compliant_Result.get(j));
                            }

                            int componentComplianceCount = 0;
                            for (int z = 0; z < component_Result.size(); z++) {
                                if (component_Result.get(z).getIsSuccess() == 1) {
                                    componentComplianceCount++;
                                }
                            }
                            float componentComplianceRate = (float) componentComplianceCount
                                    / (float) component_Result.size();
                            Element component = result.addElement("component");
                            Properties prop = new Properties();
                            InputStream is = BigDataServiceImpl.class
                                    .getResourceAsStream("/dispatcher/componentNameCode.properties");
                            try {
                                prop.load(is);
                                is.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            component.addAttribute("name",
                                    prop.getProperty(compliants.get(0).getStandard_Source().getComp_Name()));
                            component.addAttribute("complianceRate",
                                    String.valueOf(componentComplianceRate * 100) + "%");
                            component.addAttribute("complianceCount", String.valueOf(componentComplianceCount));
                            component.addAttribute("uncompolianceCount",
                                    String.valueOf(component_Result.size() - componentComplianceCount));
                            component.addAttribute("totalCount", String.valueOf(component_Result.size()));
                            Element detail = component.addElement("detail");
                            for (int z = 0; z < compliants.size(); z++) {
                                Element resultSet = detail.addElement("resultSet");
                                Element serialnumber = resultSet.addElement("serialnumber");
                                serialnumber.setText(compliants.get(z).getCompliantnumber());
                                Element compliancenumber = resultSet.addElement("compliancenumber");
                                compliancenumber.setText(compliants.get(z).getStandard_Source().getCompliant_No());
                                Element compliance = resultSet.addElement("compliance");
                                if (component_Result.get(z).getIsSuccess() == 1) {
                                    compliance.setText("true");
                                } else {
                                    compliance.setText("false");
                                }
                                Element name = resultSet.addElement("name");
                                name.setText(compliants.get(z).getStandard_Source().getCompliant_Name());
                                Element des = resultSet.addElement("des");
                                des.setText(compliants.get(z).getStandard_Source().getContent());
                                Element standard = resultSet.addElement("standard");
                                standard.setText(compliants.get(z).getStandard_Source().getCheckstandard());
                                Element checkStep = resultSet.addElement("checkStep");
                                checkStep.setText(compliants.get(z).getStandard_Source().getCheckstep());
                            }

                            if (compliant.getStandard_Source().getId() != compliants.get(0).getStandard_Source()
                                    .getId()) {
                                component_Result = new ArrayList<compliant_Result>();
                                component_Result.add(compliant_Result.get(j));
                                compliants = new ArrayList<compliant>();
                                compliants.add(compliant);
                            }
                        } else {
                            component_Result.add(compliant_Result.get(j));
                            compliants.add(compliant);
                        }
                    }
                    if (!(compliant_Result.get(0).getDeviceIP().equals(compliantResults.get(i).getDeviceIP()))) {
                        compliant_Result = new ArrayList<compliant_Result>();
                        compliant_Result.add(compliantResults.get(i));
                    }
                } else {
                    compliant_Result.add(compliantResults.get(i));
                }
            }
        }

        OutputFormat of = OutputFormat.createPrettyPrint();
        of.setEncoding("UTF-8");
        // of.setSuppressDeclaration(true);
        of.setIndent(true);
        of.setIndent("    ");
        of.setNewlines(true);
        StringWriter sw = new StringWriter();
        try {
            XMLWriter xw = new XMLWriter(sw, of);
            xw.write(document);
            xw.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sw.toString();
    }

    public static void main(String[] args) {
        Document document = DocumentHelper.createDocument();
        Element root = document.addElement("root");
        {
            Element deep = root.addElement("deep");
            deep.setText("deep");
            {
                deep.addElement("moredeep");
            }
        }
        OutputFormat of = OutputFormat.createPrettyPrint();
        of.setEncoding("UTF-8");
        // of.setSuppressDeclaration(true);
        of.setIndent(true);
        of.setIndent("    ");
        of.setNewlines(true);
        StringWriter sw = new StringWriter();
        try {
            XMLWriter xw = new XMLWriter(sw, of);
            xw.write(document);
            xw.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(sw.toString());
    }
}
